package com.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestThreadRennLock {

    private static final Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(() -> test(), "线程A").start();

        new Thread(() -> test(), "线程B").start();
    }

    private static void test() {
        try {
            if (lock.tryLock(3,TimeUnit.SECONDS)){
                System.out.println(Thread.currentThread().getName() + "获得了锁");
            }else {
                System.out.println(Thread.currentThread().getName() + "没有获得了锁");
                return;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "释放了锁");
            lock.unlock();
        }


    }
}
